import os
import sys
import zipfile
import optparse

'''
Created on 2009-5-27

@author: Timothy
'''

class Jad(object):
    def __init__(self, text = None):
        self.__props = {}
        
        if text:
            self.update(text)
    
    def update(self, text):
        lines = filter(len, map(str.strip,text.split('\n')))
        for line in lines:
            k, v = map(str.strip, line.split(':'))
            self.__props[k] = v
    
    def dumps(self):
        return ''.join(['%s: %s\r\n'%(k,v) for k,v in self.__props.items()])
    
    def __getitem__(self, k):
        return self.__props[k]
    
    def __setitem__(self, k, v):
        self.__props[k] = v
    
    def __delitem__(self, k):
        del self.__props[k]
    

def create_jad(jar_path, jad_file = None, override = False):
    """ create a jad file for the given jar file.
    
        jar_path: path to jar file
        jad_path: path to new jad file. if None, it will be same name and in 
                  the same directory with the jar file
    """
    
    assert jar_path.lower().endswith('.jar'), 'jar_path must ends with ".jar"'    
    
    if jad_file is None:
        jad_file = jar_path[:-3] + 'jad'
    
    if not override and os.path.exists(jad_file):
        raise Exception('File %s already exists.' % jad_file)        
    
    zf = zipfile.ZipFile(jar_path)
    mf = zf.read('META-INF/MANIFEST.MF')
    jad = Jad(mf)
    open(jad_file, 'wb').write(jad.dumps())
    return jad_file

def main():
    usage = '''
usage:  jad.py [options] command args

        jad.py create [-o] <jar_file> [<jad_file>]

options:
        -o --override         override existing files.
                 
'''
    parser = optparse.OptionParser(usage) 
    parser.add_option("-o", "--override", dest="override", action="store_true",
                      default=False, help="override existing files.")
       
    (options, args) = parser.parse_args()
    
    if len(args):
        cmd,args = args[0], args[1:]
        if cmd == 'create':
            if len(args) in [1,2]:
                try:
                    jad_file = create_jad(args[0], len(args)>1 and args[1] or None, options.override)
                    print 'Jad file created: %s' % jad_file
                except Exception, e:
                    print 'Error creating jad file:', str(e)
                return            
            
    print usage

if __name__ == '__main__':
    main()
    